import loginApi from '@/api/system/login';
import authorityApi from '@/api/system/auth';
import { utils } from '@/utils/utils';
import { getToken, setToken, removeToken, setStorage, removeStorage } from '@/utils/auth';
import Vue from 'vue';
import * as stn from '../../constants/storeName';
import socketInstance from '../../utils/socket';

// 获取菜单 -- 已合并至loginApi.getUserInfoByToken
function getUserMenuList() {
  authorityApi.getUserMenuList({}).then((response) => {
    if (response.status === 0) {
      setStorage(stn.MENU_LIST, response.data.menuList);
      setStorage(stn.MENUS_PERMISSION, response.data.menusPermission);
      //debugger
      //window.location.reload()
    } else {
      utils.notifyError(response.msg);
    }
  });
}

function socketMessage(data) {}

const user = {
  state: {
    userInfo: null,
    userId: undefined,
    userRole: undefined, //1.康来管理员 3.商户 5.社区管理员、维护员
    relationRoleId: undefined,
    isRemind: 0, // 是否需要消息提醒(0.否 1.是)
    unCallPoliceMsgCount: 0, // 未读报警消息总数
    unReadCount: 0, // 未读消息总数
    token: getToken(),
    name: '',
    detailRole: '',
    roles: [], // 角色id集合
    userList: [],
    tenantList: [],
    tenantId: '',
    tenantName: '',
  },

  mutations: {
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_USERID: (state, userId) => {
      state.userId = userId;
    },
    SET_USERROLE: (state, userRole) => {
      state.userRole = userRole;
    },
    SET_DETAILROLE: (state, detailRole) => {
      state.detailRole = detailRole;
    },
    SET_UN_READ_COUNT: (state, unReadCount) => {
      state.unReadCount = unReadCount;
    },
    SET_UN_READ_CALL_POLICE_COUNT: (state, unCallPoliceMsgCount) => {
      state.unCallPoliceMsgCount = unCallPoliceMsgCount;
    },
    SET_RELATIONROLEID: (state, relationRoleId) => {
      state.relationRoleId = relationRoleId;
    },
    SET_IS_REMIND: (state, isRemind) => {
      state.isRemind = isRemind;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_USERLIST: (state, userList) => {
      state.userList = userList;
    },
    SET_TENANTLIST: (state, tenantList) => {
      state.tenantList = tenantList;
    },
    SET_TENANTID: (state, tenantId) => {
      state.tenantId = tenantId;
    },
    SET_TENANTNAME: (state, tenantName) => {
      state.tenantName = tenantName;
    },
  },

  actions: {
    // 获取用户信息
    async GetUserInfo({ commit, dispatch, state }) {
      // 获取菜单信息
      //getUserMenuList();
      // 获取用户登录信息
      const response = await loginApi.getUserInfoByToken(state.token);
      const data = response.data;
      // 获取用户列表，可以切换登录
      //const response2 = await loginApi.getUserList({userId:data.id})
      // 获取租户列表，可以切换登录
      //const response3 = await loginApi.getTenantList({userId:data.id})
      //debugger

      let userInfo = {
        id: data.id,
        name: data.name,
        detailRole: data.detailRole,
        userRole: data.userRole,
        relationRoleId: data.relationRoleId,
        isRemind: data.isRemind,
        roles: data.roleIds,
        //userList: response2.data||[],
        //tenantList: response3.data||[],
        tenantId: data.tenantId,
        tenantName: data.tenantName,
      };
      setStorage(stn.LOGIN_STATUS, true);
      setStorage(stn.USER_INFO, userInfo);
      setStorage(stn.MENU_LIST, data.menuList);
      setStorage(stn.MENUS_PERMISSION, data.menusPermission);
      commit('SET_USER_INFO', userInfo);
      commit('SET_USERID', userInfo.id);
      commit('SET_NAME', userInfo.name);
      commit('SET_DETAILROLE', userInfo.detailRole);
      commit('SET_USERROLE', userInfo.userRole);
      commit('SET_RELATIONROLEID', userInfo.relationRoleId);
      commit('SET_IS_REMIND', userInfo.isRemind);
      //commit('SET_USERLIST', userInfo.userList)
      //commit('SET_TENANTLIST', userInfo.tenantList)
      commit('SET_TENANTID', userInfo.tenantId);
      commit('SET_TENANTNAME', userInfo.tenantName);
      if (userInfo.roles && userInfo.roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        commit('SET_ROLES', userInfo.roles);
      } else {
        return Promise.reject('找不到系统用户请联系您的系统管理员进行配置🛠️!');
      }

      if (localStorage.getItem('istokenOne') !== '1') {
        socketInstance.open();
        socketInstance.emit('authorization', userInfo.id);
        localStorage.setItem('istokenOne', '1');
      } else {
        socketInstance.emit('refresh', userInfo.id);
      }

      return response;
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        loginApi
          .sysUserLoginOut(state.token)
          .then(() => {
            removeStorage(stn.LOGIN_STATUS);
            removeStorage(stn.USER_INFO);
            removeStorage(stn.MENU_LIST);
            removeStorage(stn.MENUS_PERMISSION);
            removeStorage('istokenOne');
            commit('SET_USER_INFO', {});
            commit('SET_TOKEN', '');
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '');
        removeToken();
        resolve();
      });
    },
    setToken({ commit }, token) {
      commit('SET_TOKEN', token);
      // 存入cookies
      setToken(token);
    },
    setUnReadCount({ commit }, unReadCount) {
      commit('SET_UN_READ_COUNT', unReadCount);
    },
    setUnCallPoliceMsgCount({ commit }, unCallPoliceMsgCount) {
      commit('SET_UN_READ_CALL_POLICE_COUNT', unCallPoliceMsgCount);
    },
  },
};

export default user;
